<template>
  <!-- 新增 -->
  <div class="addNotice">
    <el-card class="list-box">
      <div slot="header" class="table_header">
        <span>新增公告</span>

      </div>
      <div class="list-container">
        <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm">
          <el-form-item label="公告名称" prop="title">
            <el-input v-model="ruleForm.title" style="width: 25%;" />
          </el-form-item>
          <el-form-item label="公告副标题" prop="subtitle">
            <el-input v-model="ruleForm.subtitle" style="width: 25%;" />
          </el-form-item>
          <el-form-item label="正文" prop="content">
            <!-- 图片上传组件辅助 -->
            <el-upload
              class="avatar-uploader"
              :action="editorOption.serverUrl"
              name="file"
              :headers="editorOption.headerObj"
              :auto-upload="true"
              :show-file-list="false"
              :on-success="uploadSuccess"
              :on-error="uploadError"
              :before-upload="beforeUpload"
              style="display: none;"
            />
            <quill-editor
              ref="myQuillEditor"
              v-model.lazy.trim="ruleForm.content"
              class="editor"
              :options="editorOption"
              @blur="onEditorBlur($event)"
              @focus="onEditorFocus($event)"
              @ready="onEditorReady($event)"
              @change="onEditorChange($event)"
            />

          </el-form-item>
          <el-form-item label="分类" prop="title">
            <el-select
              v-model="ruleForm.classification"
              multiple
              clearable
              filterable
              placeholder="请选择"
              style="width: 25%;"
            >
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="排序" prop="serialNumber">
            <el-input-number v-model="ruleForm.serialNumber" style="width: 25%;" controls-position="right" :min="0" :max="999" />
          </el-form-item>
          <el-form-item label="是否置顶">
            <el-switch
              v-model="ruleForm.isTop"
              active-color="#42b983"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

    </el-card>

  </div>
</template>

<script>
  import {
    quillEditor
  } from 'vue-quill-editor'
  import 'quill/dist/quill.core.css'
  import 'quill/dist/quill.snow.css'
  import 'quill/dist/quill.bubble.css'
  import '@/assets/quill.scss'
  import {
    getToken
  } from '@/utils/auth'
  export default {
    components: {
      quillEditor
    },
    data() {
      const toolbarOptions = [
        ['bold', 'italic', 'underline', 'strike'], // toggled buttons
        [{
          'header': 1
        }, {
          'header': 2
        }], // custom button values
        [{
          'list': 'ordered'
        }, {
          'list': 'bullet'
        }],
        [{
          'indent': '-1'
        }, {
          'indent': '+1'
        }], // outdent/indent
        [{
          'direction': 'rtl'
        }], // text direction
        [{
          'size': ['small', false, 'large', 'huge']
        }], // custom dropdown
        [{
          'header': [1, 2, 3, 4, 5, 6, false]
        }],
        [{
          'color': []
        }, {
          'background': []
        }], // dropdown with defaults from theme
        [{
          'font': []
        }],
        [{
          'align': []
        }],
        ['link', 'image'],
        ['clean']
      ]

      return {
        loading: '',
        // 富文本配置
        editorOption: {
          placeholder: '请输入相关内容',
          modules: {
            toolbar: {
              container: toolbarOptions,
              handlers: {
                'image': function(value) {
                  if (value) {
                    document.querySelector('.avatar-uploader input').click()
                  } else {
                    this.quill.format('image', false)
                  }
                }
              }
            }
          },
          // 此项配置是选择图片之后的上传路径
          serverUrl: `${process.env.VUE_APP_BEG_IP}xboot/upload/file`,
          headerObj: {
            accessToken: getToken()
          }
        },

        ruleForm: {
          title: '',
          subtitle: '', // 副标题
          content: '', // 正文
          isTop: 0, // 是否置顶
          classification: [], // 分类id
          classificationValue: [],
          serialNumber: 0

        },
        rules: {
          title: [{
            required: true,
            message: '请输入公告名称',
            trigger: 'blur'
          }],
          subtitle: [{
            required: true,
            message: '请输入公告副标题',
            trigger: 'blur'
          }],
          content: [{
            required: true,
            message: '请输入公告正文',
            trigger: 'blur'
          }],
          serialNumber: [{
            required: true,
            message: '请输入排序',
            trigger: 'blur'
          }]
        },
        options: [{
            value: '0',
            label: '首页'
          },
          {
            value: '1',
            label: '车间'
          },
          {
            value: '2',
            label: '安全'
          },
          {
            value: '3',
            label: '质量'
          },
          {
            value: '4',
            label: '电气'
          },
          {
            value: '5',
            label: '质量'
          }
        ]
      }
    },
    methods: {
      // 监听富文本编辑框动向，敌不动我不动敌若动我乱动，还有个上传图片
      onEditorChange({
        editor,
        html,
        text
      }) {
        // 此处三项可以自己在控制台打印
        this.ruleForm.content = html
      },

      beforeUpload(file) {
        this.loading = this.$loading({
          lock: true,
          text: '图片加载中，请稍后！',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
      },

      // 上传成功
      uploadSuccess(res, file) {
        // 获取富文本组件实例
        const quill = this.$refs.myQuillEditor.quill
        if (res.code === 200) {
          // 获取光标所在位置
          const length = quill.getSelection().index
          // 获取光标所在位置// 获取光标所在位置
          const imgres = `http://${res.result}`
          quill.insertEmbed(length, 'image', imgres)
          // 调整光标到最后
          quill.setSelection(length + 1)
        } else {
          this.$message.error(res.message)
        }
        this.loading.close()
      },
      // 上传失败来到这里
      uploadError() {
        this.loading.close()
        this.$message.error('上传失败!')
      },
      // 提交
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.ruleForm.classificationValue = []
            if (this.ruleForm.classification.length > 0) {
              this.ruleForm.classification.forEach(item => {
                this.options.forEach((it) => {
                  if (item === it.value) {
                    this.ruleForm.classificationValue.push(it.label)
                  }
                })
              })
            } else {
              this.resetForm.classificationValue = []
            }
            this.ruleForm.classificationValue = [...new Set(this.ruleForm.classificationValue)]
            const data = {
              title: this.ruleForm.title,
              subtitle: this.ruleForm.subtitle,
              content: this.ruleForm.content, // 正文
              isTop: this.ruleForm.isTop, // 是否置顶
              classification: this.ruleForm.classification.join(','),
              classificationValue: this.ruleForm.classificationValue.join('/'),
              serialNumber: this.ruleForm.serialNumber
            }
            this.$Http.addAnnouncement(JSON.stringify(data)).then(res => {
              console.log('RES', res)
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: res.message
                })
                this.$router.go(-1)
              } else {
                this.$message({
                  type: 'error',
                  message: res.message
                })
              }
            }).catch(err => {
              console.log('err', err)
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      // 重置
      resetForm(formName) {
        this.$refs[formName].resetFields()
      },
      // 改变置顶
      handleStatusChange() {

      },
      // 监听编辑器事件，此处三个事件可以自己根据业务定义
      onEditorBlur(quill) {},
      onEditorFocus(quill) {},
      onEditorReady(quill) {}

    }
  }
</script>

<style lang="scss" scoped>
  // .page-content {
  //   width: 100%;
  //   height: 100%;

  //   /deep/ .editor {
  //     margin-top: 15px;

  //     .ql-editor {
  //       min-height: 300px;
  //     }
  //   }

  //   .header {
  //     padding-bottom: 15px;
  //     border-bottom: 1px solid #eee;
  //   }

  //   /deep/ .el-form {
  //     .el-form-item {
  //       max-width: 700px;
  //     }
  //   }

  //   /* 此处是隐藏上传按钮的样式 */
  //   /deep/ .disabled .el-upload--picture-card {
  //     display: none;
  //   }
  // }
</style>

<style lang="scss" scoped>
  .addNotice {
    padding: 10px 10px 0 10px;

    .list-box {
      margin-top: 10px;

      .table_header {
        display: flex;
        width: 100%;
        justify-content: space-between;
        align-items: center;

      }

      .list-container {
        padding: 50px;
        box-sizing: border-box;
      }
    }
  }
</style>
